package com.jbh.netlibrary.u;

import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


/**
 *
 * 实时获取网络速度
 *
 */
public class NetSeepUtil {

    private long total_data = TrafficStats.getTotalTxBytes();
    private int count = 1;
    private String seep;//网速


    /**
     *
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 > (1024 * 1024)) {
                seep = msg.arg1 / 1024 / 1024 + "Mb/s";
            } else if (msg.arg1 > 1024) {
                seep = msg.arg1 / 1024 + "Kb/s";
            } else {
                seep = msg.arg1 + "b/s";
            }
            Log.v("[NetSeepUtil]","[NetSeepUtil]->seep="+seep);
        }
    };


    /**
     * 定义线程周期性的获取网速
     */
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(mRunnable, count * 1000);
            Message msg = mHandler.obtainMessage();
            msg.arg1 = getNetSpeed();
            mHandler.sendMessage(msg);
        }
    };


    private int getNetSpeed() {
        long traffic_data = TrafficStats.getTotalTxBytes() - total_data;//总的发送的字节数
        total_data = TrafficStats.getTotalTxBytes();
        return (int) (traffic_data / count);
    }


    /**
     * 开启实时获取网络速度
     */
    public void startNet(){
        mHandler.postDelayed(mRunnable, 100);
    }


    /**
     */
    public void stop(){
        if (mHandler!=null){
            mHandler.removeCallbacks(mRunnable);
        }
    }
}
